package com.smartfast4j.backend.modules.sys.security.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.text.MessageFormat;

/**
 * 实现Shiro无状态访问，如通过传递sessionid参数即可实现会话访问
 * 这里需要自定义Shiro的SessionManager类，方法是继承org.apache.shiro.web.session.mgt.DefaultWebSessionManager类，重载getSessionId方法
 * Created by gacl on 2017/9/7.
 */
public class SessionManager extends DefaultWebSessionManager {

    private static final Logger logger = Logger.getLogger(SessionManager.class);

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String token = request.getParameter("token");
        logger.debug("进入shiro SessionManager，获取到的登录用户token="+token);
        if(StringUtils.isNotEmpty(token) && !token.equals("null")){
            // 设置当前session状态
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                    ShiroHttpServletRequest.URL_SESSION_ID_SOURCE); // session来源与url
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, token);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return token;
        }/*else{
            return super.getSessionId(request, response);
        }*/
        return null;
    }
}
